/*
 * $Id: Main.java 172 2009-06-02 10:54:03Z meyer@alphatec.de $
 * 
 *
 * Copyright 2009 DeltaDesk
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
 * implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package deltadesk.apps.pictureviewer;

import java.awt.Color;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.util.Arrays;

import javax.swing.JFrame;

/**
 * Main
 * 
 * @author Andreas Meyer
 * @version $Revision: 172 $
 */
public class Main {

	/** The current index in the files array. */
	private int index;


	/**
	 * Construct the main class.
	 * 
	 * @param dirStr
	 */
	public Main(final String dirStr) {
		
		final File dir = new File(dirStr);
		final File[] files = dir.listFiles(new FilenameFilter() {

			public boolean accept(final File dir, final String name) {
				return name.endsWith(".jpg") || name.endsWith(".JPG");
			}

		});
		Arrays.sort(files);
		
		final PictureViewer pictureViewer = new PictureViewer();
		try {
			pictureViewer.setSource(files[0]);
		} catch (IOException e) {
			e.printStackTrace();
		}

		final JFrame window = new JFrame();
		window.setUndecorated(true);
		window.setBackground(Color.BLACK);
		window.getContentPane().add(pictureViewer);

		window.addKeyListener(new KeyAdapter() {

			public void keyPressed(final KeyEvent ke) {
				
				// next
				if(ke.getKeyCode() == KeyEvent.VK_SPACE) {
					
					if(index+1 < files.length) index++;
					try {
						pictureViewer.setSource(files[index]);
					} catch (IOException e) {
						e.printStackTrace();
					}
					
				// previous
				} else if(ke.getKeyCode() == KeyEvent.VK_BACK_SPACE) {
					
					if(index > 0) index--;
					try {
						pictureViewer.setSource(files[index]);
					} catch (IOException e) {
						e.printStackTrace();
					}
					
				// exit
				} else if(ke.getKeyCode() == KeyEvent.VK_ESCAPE) {
					System.exit(0);
				}
			}
		});
		
		DisplayUtil.hideMouseCursor(window);
		
		final GraphicsEnvironment env = GraphicsEnvironment.getLocalGraphicsEnvironment();
		final GraphicsDevice device = env.getDefaultScreenDevice();
		device.setFullScreenWindow(window);
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		
		if (args.length > 0) {
			new Main(args[0]);
		} else {
			System.out.println("Usage: deltadesk-pictureviewer <filename>");
		}

	}

}
